﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections;
using System.Threading;
namespace DAO
{
    public class DataProvider
    {
        private static SqlConnection _con = null;

        static DataProvider()
        {
            //lấy chuỗi kết nối từ web.config
            string strConnection = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString.ToString();
            _con = new SqlConnection(strConnection);
        }

        // thực thi câu truy vấn sql
        public DataTable ExecuteQuery(string strQuery)
        {
            DataTable resTable = new DataTable();

            try
            {
                _con.Open();

                SqlDataAdapter adapter = new SqlDataAdapter(strQuery, _con);

                adapter.Fill(resTable);
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
            finally
            {
                _con.Close();
            }

            return resTable;
        }

        // thực thi câu truy vấn bằng StoreProcedure
        public DataTable ExecuteStoreProc(string storeProcName, IList<SqlParameter> arrParameter)
        {
            DataTable resTable = new DataTable();
            try
            {
                _con.Open();

                SqlCommand cmd = new SqlCommand(storeProcName, _con);
                cmd.CommandText = storeProcName;
                cmd.CommandType = CommandType.StoredProcedure;

                //Lay so parameter
                int N = arrParameter.Count;
                for (int i = 0; i < N; i++)
                {
                    cmd.Parameters.Add(arrParameter[i]);
                }

                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(resTable);

            }
            catch (Exception ex)
            {
                throw new Exception("Lỗi khi thực thi stored procedure: " + ex.Message);
            }
            finally
            {
                _con.Close();
            }

            return resTable;
        }
    }
}
